package vip.xiaonuo.smzq.modular.lifecycle.controller.module;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.common.pojo.CommonResult;
import vip.xiaonuo.smzq.modular.kcl.entity.Zlsc;
import vip.xiaonuo.smzq.modular.lifecycle.base.Base;
import vip.xiaonuo.smzq.modular.lifecycle.base.QueryLifeCycleBase;
import vip.xiaonuo.smzq.modular.lifecycle.constant.LifeCycleConstant;
import vip.xiaonuo.smzq.modular.lifecycle.entity.*;
import vip.xiaonuo.smzq.modular.lifecycle.mapper.entity.KclCb06KcMapper;
import vip.xiaonuo.smzq.modular.lifecycle.mapper.entity.KclWjglbMapper;
import vip.xiaonuo.smzq.modular.lifecycle.mapper.entity.LifeCycleMineralMeaMapper;
import vip.xiaonuo.smzq.modular.lifecycle.mapper.module.LifeCycleMapper;
import vip.xiaonuo.smzq.modular.lifecycle.po.QueryAdministractiveRegionPO;
import vip.xiaonuo.smzq.modular.lifecycle.po.QueryMineInfoPO;
import vip.xiaonuo.smzq.modular.lifecycle.po.QueryMineStorePO;
import vip.xiaonuo.smzq.modular.lifecycle.po.QueryYearStorePO;
import vip.xiaonuo.smzq.modular.lifecycle.po.datamanager.*;
import vip.xiaonuo.smzq.modular.lifecycle.result.ResultWrapper;
import vip.xiaonuo.smzq.modular.lifecycle.result.WebResult;
import vip.xiaonuo.smzq.modular.lifecycle.service.entity.*;
import vip.xiaonuo.smzq.modular.lifecycle.service.factory.WrapperMeterFactory;
import vip.xiaonuo.smzq.modular.lifecycle.service.factory.produce.WrapperMeter;
import vip.xiaonuo.smzq.modular.lifecycle.service.module.LifeCycleDataManagerService;
import vip.xiaonuo.smzq.modular.lifecycle.service.module.LifeCycleHanderDataService;
import vip.xiaonuo.smzq.modular.lifecycle.service.module.LifeCycleService;
import vip.xiaonuo.smzq.modular.lifecycle.util.CoordinateTranUtil;
import vip.xiaonuo.smzq.modular.lifecycle.vo.MineCoordinateVO;
import vip.xiaonuo.smzq.modular.lifecycle.vo.QueryMineInfoRetVO;
import vip.xiaonuo.smzq.modular.lifecycle.vo.QueryMineInfoVO;
import vip.xiaonuo.smzq.modular.lifecycle.vo.QueryMineStoreVO;
import vip.xiaonuo.smzq.modular.lifecycle.vo.datamanager.LifeCycleMineMeaVO;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 全生命周期数据管理模块
 * @author geoscene_yuyanfei
 * @since 2024-03-20
 */
@Api(tags = "全生命周期数据管理模块")
@RestController
@RequestMapping("/life/cycle/datamanger")
@Validated
public class LiftCycleDataMangerController {
    @Autowired
    LifeCycleDataManagerService lifeCycleDataManagerService;

    @Autowired
    LifeCycleMineralMeaMapper lifeCycleMineralMeaMapper;

    @Autowired
    KclKsService kclKsService;

    @Autowired
    HisiKsService hisiKsService;

    @Autowired
    LifeCycleService lifeCycleService;

    @Autowired
    LifeCyclePedigeeService lifeCyclePedigeeService;

    @Autowired
    WrapperMeterFactory wrapperMeterFactory;

    @Autowired
    LifeCycleHanderDataService lifeCycleHanderDataService;

    @Autowired
    ResultWrapper resultWrapper;

    @ApiOperation(value = "分页查询矿山基本信息接口", notes = "分页查询矿山基本信息接口")
    @PostMapping(value = "/mine/list/page")
    public WebResult queryKclKsListPage(@RequestBody QueryMineListPO queryMineListPO) {

        return resultWrapper.getSuccessWebResult(lifeCycleDataManagerService.queryKclKsListPage(queryMineListPO));
    }

    @ApiOperation(value = "上传文件接口", notes = "上传文件接口接口")
    @PostMapping(value = "/upload/file")
    public WebResult uploadFile(@RequestParam("files") List<MultipartFile> files,
            @RequestParam("params")String params
    ) {
        boolean success = lifeCycleDataManagerService.uploadMeterFile(files, JSONUtil.parseObj(params).getStr("id"));

        return resultWrapper.getSuccessWebResult(success);
    }


    @ApiOperation(value = "文件批量下载接口", notes = "文件批量下载接口")
    @PostMapping(value = "/download/file")
    public void downloadFile(@RequestBody List<String> fileIds
    ) {

        lifeCycleDataManagerService.downloadFiles(fileIds);
//        return resultWrapper.getSuccessWebResult(null);
    }


    @ApiOperation(value = "查询矿石储量列表", notes = "查询矿石储量列表")
    @PostMapping(value = "/mineMeaList")
    public WebResult querymineMeaList(@RequestBody QueryLCMeaPO queryLCMeaPO) {
        List<LifeCycleMineMeaVO> result = CollUtil.newArrayList();
        List<LifeCycleMineMeaVO> list = lifeCycleMineralMeaMapper.selectJoinList(LifeCycleMineMeaVO.class
                ,new MPJLambdaWrapper<LifeCycleMineralMea>()
                .selectAll(LifeCycleMineralMea.class)
                .selectAs(KclCb06Kc::getKcmc, LifeCycleMineMeaVO::getMineralTypeName)
                .selectAs(KclCb06Kc::getJsdxmc, LifeCycleMineMeaVO::getMetalName)
                .innerJoin(KclCb06Kc.class,on->
                        on.eq(KclCb06Kc::getKcdm, LifeCycleMineralMea::getMineralType)
                        .eq(KclCb06Kc::getTjdx, LifeCycleMineralMea::getTjdx)
//                        .eq(KclCb06Kc::getKclb, LifeCycleMineralMea::getKclb)
                        )
//                .innerJoin(KclCb06Kc.class, KclCb06Kc::getKcdm, LifeCycleMineralMea::getMineralType)
                .eq(LifeCycleMineralMea::getMineStoreId, queryLCMeaPO.getMineStoreId())
        );

        list.forEach(ele->{
            ele.initMineralTypeName();
        });

        List<String> jsonStrList = CollUtil.newArrayList();
        for (LifeCycleMineMeaVO lifeCycleMineMeaVO:list) {
            String jsonStr = JSONUtil.toJsonStr(lifeCycleMineMeaVO);
            if(!CollUtil.contains(jsonStrList,jsonStr)){
                jsonStrList.add(jsonStr);
                result.add(lifeCycleMineMeaVO);
            }
        }

        if(StrUtil.equals("年报",queryLCMeaPO.getLcNodeName()) && CollUtil.size(list)==0){
            List<HisiKs> hisiKss = hisiKsService.lambdaQuery()
                    .eq(HisiKs::getDjflbh,queryLCMeaPO.getRegClassCode())
                    .eq(HisiKs::getKqbh,queryLCMeaPO.getMineralCode())
                    .eq(HisiKs::getNd,queryLCMeaPO.getYear()).list();

            for (LifeCycleMineMeaVO lifeCycleMineMeaVO:result) {
                for (HisiKs hisiKs:hisiKss) {
                    if(StrUtil.equals(hisiKs.getKcdm(), Convert.toStr(lifeCycleMineMeaVO.getMineralType()))){
                        lifeCycleMineMeaVO.setZs(Convert.toDouble(hisiKs.getKqzsl()));
                        lifeCycleMineMeaVO.setKx(Convert.toDouble(hisiKs.getKqkxl()));
                        lifeCycleMineMeaVO.setTm(Convert.toDouble(hisiKs.getKqtml()));
                        lifeCycleMineMeaVO.setKz(Convert.toDouble(hisiKs.getKqkzl()));
                        lifeCycleMineMeaVO.setTd(Convert.toDouble(hisiKs.getKqtdl()));
                        lifeCycleMineMeaVO.setDyl(Convert.toDouble(Convert.toDouble(hisiKs.getKqkcl())+Convert.toDouble(hisiKs.getKqssl())));
                    }
                }
            }
        }




        return resultWrapper.getSuccessWebResult(result);
    }

    @ApiOperation(value = "数据库中已存在的族谱矿区列表", notes = "数据库中已存在的族谱矿区列表")
    @GetMapping(value = "/queryDBExistPedigeeMineralList")
    public WebResult queryDBExistPedigeeMineralList(@RequestParam("curMinCode") String curMinCode) {
        return resultWrapper.getSuccessWebResult(lifeCycleDataManagerService.queryDBExistPedigeeMineralList(curMinCode));
    }


    @ApiOperation(value = "查询一个矿区的所有族谱节点列表", notes = "查询一个矿区的所有族谱节点列表")
    @GetMapping(value = "/queryPedigeeLifeCycleNodes")
    public WebResult queryPedigeeLifeCycleNodes(@RequestParam("mineralCode") String mineralCode) {
        return resultWrapper.getSuccessWebResult(lifeCycleDataManagerService.queryPedigeeLifeCycleNodes(mineralCode,null));
    }

    @ApiOperation(value = "新增或者保存生命周期节点", notes = "新增或者保存生命周期节点")
    @PostMapping(value = "/saveOrUpdateLCNode")
    public WebResult saveOrUpdateLCNode(@RequestBody SaveLCNodePO saveLCNodePO) {
//        if(StrUtil.equals(saveLCNodePO.getReportName(),CollUtil.getFirst(LifeCycleConstant.crePedNodTypes))){
        lifeCycleHanderDataService.initPedList(saveLCNodePO);
//        }
        return resultWrapper.getSuccessWebResult(lifeCycleDataManagerService.saveOrUpdateLCNode(saveLCNodePO));
    }


    @ApiOperation(value = "删除生命周期节点", notes = "删除生命周期周期节点")
    @PostMapping(value = "/lifeCycleNode/d")
    public WebResult lifeCycleNodeDel(@RequestBody DelLCNodePO delLCNodePO) {
        return resultWrapper.getSuccessWebResult(lifeCycleDataManagerService.lifeCycleNodeDel(delLCNodePO.getId(),delLCNodePO.getXlIndex()));
    }

//    坐标管理相关=========================================================
    @ApiOperation(value = "新增或者更新坐标接口", notes = "新增或者更新坐标接口")
    @PostMapping(value = "/saveOrUpdateCoor")
    public WebResult saveOrUpdateCoor(@RequestBody SaveOrUpdateCoorPO saveOrUpdateCoorPO) {
        return resultWrapper.getSuccessWebResult(lifeCycleDataManagerService.saveOrUpdateCoor(saveOrUpdateCoorPO));
    }

    @ApiOperation(value = "根据生命周期节点查询矿区范围坐标接口", notes = "根据生命周期节点查询矿区范围坐标接口")
    @GetMapping(value = "/queryCoorByLcNodeId")
    public WebResult queryCoorByLcNodeId(@RequestParam("id")String id) {
        return resultWrapper.getSuccessWebResult(lifeCycleDataManagerService.queryCoorByLcNodeId(id));
    }

    @ApiOperation(value = "检查节点时间是否存在接口", notes = "检查节点时间是否存在接口")
    @PostMapping(value = "/checkNodeDateExist")
    public WebResult checkNodeDateExist(@RequestBody CheckNodeDatePO checkNodeDatePO) {
        return resultWrapper.getSuccessWebResult(lifeCycleDataManagerService.checkNodeDateExist(checkNodeDatePO));
    }



    @ApiOperation(value = "模糊匹配族谱父id列表接口", notes = "模糊匹配族谱父id列表接口")
    @GetMapping(value = "/likePedPid")
    public WebResult likePedPid(@RequestParam("parentId") String parentId) {
        List<LifeCyclePedigee> pedigees = lifeCyclePedigeeService.lambdaQuery().like(LifeCyclePedigee::getParentId, parentId).list();
        return resultWrapper.getSuccessWebResult(pedigees);
    }

    @ApiOperation("查询全生命周期列表(生命周期管理)")
    @PostMapping("/queryLCNodeList")
    public WebResult queryList(@RequestBody QueryMineStorePO queryMineStorePO) {
        List<QueryMineStoreVO> queryMineStoreVOS = lifeCycleService.queryLifeCycleMineList(queryMineStorePO,false);
        queryMineStoreVOS = lifeCycleService.handYearReport(queryMineStoreVOS);
        queryMineStoreVOS = lifeCycleService.handerMerge(queryMineStoreVOS);
        queryMineStoreVOS = wrapperMeterFactory.getProduce(WrapperMeter.revRecWrapperMeterServiceName).wrapper(queryMineStoreVOS);

        if(CollUtil.size(queryMineStoreVOS)!=0){
            lifeCycleService.initFirstPedigee(queryMineStoreVOS);
        }

        return resultWrapper.getSuccessWebResult(queryMineStoreVOS);
    }

    @ApiOperation("查询坐标根据三个基本参数")
    @PostMapping("/queryCoorByBaseParams")
    public WebResult queryCoorByBaseParams(@RequestBody QueryLifeCycleBase queryLifeCycleBase) {
        return resultWrapper.getSuccessWebResult(lifeCycleDataManagerService.queryCoorByBaseParams(queryLifeCycleBase));
    }

    @ApiOperation("验证坐标的合法性")
    @PostMapping("/checkCoorTrue")
    public WebResult checkCoorTrue(@RequestBody Dict params) {
        return resultWrapper.getSuccessWebResult(lifeCycleDataManagerService.checkCoorTrue(params.getStr("coorStr")));
    }

    @ApiOperation("得到坐标对象列表")
    @PostMapping("/getCoorItemByCoorStr")
    public WebResult getCoorItemByCoorStr(@RequestBody Dict params) {
        return resultWrapper.getSuccessWebResult(lifeCycleDataManagerService.getCoorItemByCoorStr(params.getStr("coorStr")));
    }

//    =====================================================================

}
